package com.yuyang.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yuyang.common.constant.AuthServerConstants;
import com.yuyang.common.constant.CartConstant;
import com.yuyang.common.utils.R;
import com.yuyang.gulimall.cart.feign.ProductFeignService;
import com.yuyang.gulimall.cart.intercepter.CartIntercepter;
import com.yuyang.gulimall.cart.service.CartService;
import com.yuyang.gulimall.cart.vo.CartItemVo;
import com.yuyang.gulimall.cart.vo.CartVo;
import com.yuyang.gulimall.cart.vo.SkuInfoVo;
import com.yuyang.gulimall.cart.vo.UserInfoTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author yu yang
 * @date 2023/1/29 -11:27
 */
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    ThreadPoolExecutor executor;
    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public CartItemVo addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> boundHashOps = getOperations();
        String jsonStr = (String) boundHashOps.get(skuId.toString());
        CartItemVo cartItem = JSON.parseObject(jsonStr, CartItemVo.class);
        //购物车有此商品，修改商品数量
        if (cartItem != null){
            cartItem.setCount(cartItem.getCount()+num);
            boundHashOps.put(skuId.toString(),JSON.toJSONString(cartItem));
            return cartItem;
        }else {
            //新增商品到购物车
            CartItemVo cartItemVo = new CartItemVo();
            cartItemVo.setSkuId(skuId);
            cartItemVo.setCount(num);
            CompletableFuture<Void> skuInfoTask = CompletableFuture.runAsync(() -> {
                R r = productFeignService.getSkuInfo(skuId);
                if (r.getCode() == 0) {
                    SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                    });
                    cartItemVo.setImage(skuInfo.getSkuDefaultImg());
                    cartItemVo.setTitle(skuInfo.getSkuTitle());
                    cartItemVo.setPrice(skuInfo.getPrice());
                }
            }, executor);

            CompletableFuture<Void> skuAttrValuesTask = CompletableFuture.runAsync(() -> {
                R skuAttrValues = productFeignService.getSkuAttrValues(skuId);
                if (skuAttrValues.getCode() == 0) {
                    List<String> data = skuAttrValues.getData("data", new TypeReference<List<String>>() {
                    });
                    cartItemVo.setSkuAttrValues(data);
                }
            }, executor);

            CompletableFuture.allOf(skuInfoTask, skuAttrValuesTask).get();

            boundHashOps.put(skuId.toString(),JSON.toJSONString(cartItemVo));
            return cartItemVo;
        }
    }

    @Override
    public CartItemVo getCartItemById(Long skuId) {
        BoundHashOperations<String, Object, Object> operations = getOperations();
        String jsonStr = (String) operations.get(skuId.toString());
        return JSON.parseObject(jsonStr,CartItemVo.class);
    }

    @Override
    public void deleteIdCartInfo(Integer skuId) {
        getOperations().delete(skuId.toString());
    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        CartItemVo cartItemVo = getCartItemById(skuId);
        cartItemVo.setCount(num);
        getOperations().put(skuId.toString(),JSON.toJSONString(cartItemVo));
    }

    @Override
    public void checkItem(Long skuId, Integer checked) {
        CartItemVo cartItemVo = getCartItemById(skuId);
        cartItemVo.setCheck(checked == 1);
        getOperations().put(skuId.toString(),JSON.toJSONString(cartItemVo));
    }

    @Override
    public CartVo getCart() throws ExecutionException, InterruptedException {
        CartVo cartVo = new CartVo();
        UserInfoTo userInfoTo = CartIntercepter.threadLocal.get();
        String tempCartKey = CartConstant.CACHE_CART_KEY_PRIFIX + userInfoTo.getUserKey();
        //已登录
        if (userInfoTo.getUserId()!= null){
            //如果临时购物车的数据还未进行合并
            List<CartItemVo> tempCartItems = getCartItems(tempCartKey);
            if (tempCartItems != null) {
                //临时购物车有数据需要进行合并操作
                for (CartItemVo item : tempCartItems) {
                    addToCart(item.getSkuId(),item.getCount());
                }
                //清除临时购物车的数据
                redisTemplate.delete(tempCartKey);
            }
            cartVo.setItems(getCartItems(CartConstant.CACHE_CART_KEY_PRIFIX + userInfoTo.getUserId()));
        }else {
            List<CartItemVo> cartItems = getCartItems(tempCartKey);
            cartVo.setItems(cartItems);
        }
        return cartVo;
    }

    @Override
    public List<CartItemVo> getCheckItems() {
        UserInfoTo userInfoTo = CartIntercepter.threadLocal.get();
        if (userInfoTo.getUserId() == null){
            return null;
        }
        List<CartItemVo> cartItems = getCartItems(CartConstant.CACHE_CART_KEY_PRIFIX + userInfoTo.getUserId());
        if (cartItems != null && cartItems.size() > 0){
            List<CartItemVo> collect = cartItems.stream().filter(CartItemVo::getCheck).peek(cartItemVo -> {
                //更新最新的价格
                BigDecimal price = productFeignService.getPriceBySkuId(cartItemVo.getSkuId());
                cartItemVo.setPrice(price);
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    private List<CartItemVo> getCartItems(String cartKey) {
        List<Object> values = redisTemplate.boundHashOps(cartKey).values();
        if (values != null && values.size() > 0){
            return values.stream().map((item) -> {
                String jsonStr = (String) item;
                return JSON.parseObject(jsonStr, CartItemVo.class);
            }).collect(Collectors.toList());
        }
        return null;
    }

    private BoundHashOperations<String, Object, Object> getOperations() {
        UserInfoTo userInfoTo = CartIntercepter.threadLocal.get();
        String cartKey = CartConstant.CACHE_CART_KEY_PRIFIX;
        if (userInfoTo.getUserId() != null){
            cartKey += userInfoTo.getUserId();
        }else {
            cartKey += userInfoTo.getUserKey();
        }
        return redisTemplate.boundHashOps(cartKey);
    }
}
